<template>
  <div class="home">
    <div class="descktop" style="">
      <div class="descktop-menu">
        <div v-for="(x, y) in designs" :key="y" @click="selectType(y)" :class="typeIdx == y ? 'active' : ''">
          <span>{{ x.label }}</span>
          <div v-if="typeIdx == y"></div>
        </div>
      </div>
      <div class="descktop-set">
        <div class="link" @click="goPath">
          数据库
        </div>
        <div @click="addCom">增加组件</div>
        <div @click="sortDesck">排序</div>
        <div>设置</div>
      </div>
    </div>
    <template v-if="typeIdx == 2">
      <div class="descktop-content">
        <kapian />
      </div>
    </template>
    <template v-else>
      <div class="descktop-content" v-if="finished">
        <el-row :gutter="24">
          <el-col :span="span" v-for="x in designs[typeIdx].children">
            <template v-for="a in x.children">
              <component :is="homeCom[a.name]" :title="a.label" />
            </template>
          </el-col>
        </el-row>
      </div>
    </template>
    <el-dialog title="桌面排序" v-model="isSort" width="500px" draggable>
      <el-tree :data="designs" draggable />
      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
        <el-button type="primary" @click="saveSort">保 存</el-button>
        <el-button @click="() => { isSort = false }">取 消</el-button>
      </div>
    </el-dialog>
    <cycform :show="isAdd" :columns="columns" :data="form" :last="lastData" @submit="submit"
      @close="() => { isAdd = false }" />
  </div>
</template>
<script setup>
import { onMounted, ref, onUnmounted, defineAsyncComponent, getCurrentInstance } from 'vue';
import kapian from '@/components/home/kapian.vue'
import cycform from '@/components/common/form.vue';
import codes  from '@/utils/codes';
import { useRouter } from 'vue-router'
const { proxy } = getCurrentInstance()
const router = useRouter()
onMounted(() => {
  getDesign()
  handleResize()
  window.addEventListener("resize", handleResize);
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 自动载入指定目录组件
const files = import.meta.glob('@/components/home/*.vue');
const homeCom = {}
for (const key in files) {
  const name = key.split('/').pop()?.replace('.vue', '');
  homeCom[name] = defineAsyncComponent(files[key]);
}

// 加载各种组件
const designs = ref([])
const all = ref([])
const options = ref([])
const span = ref(6)
const typeIdx = ref(0)
const isSort = ref(false)
const finished = ref(false)
const lastData = ref({})

// 获取数据
const getDesign = () => {
  finished.value = false
  proxy.$service.queryData({
    table: 'designs',
    data: {
    },
    query: {
      page: 1,
      show: 100
    },
    pid: true,
    sort: true
  }).then(res => {
    designs.value = proxy.$global.arrayToTree(res.data, "pid", 0)
    all.value = proxy.$global.arrayToTree(res.data, "pid", 0)
    options.value = getOptions(res.data)
    lastData.value = res.data[res.data.length - 1]
    finished.value = true
  })
}

const goPath = ()=>{
  router.push('/manager')
}

const getOptions = (list) => {
  let arr = []
  list.map(x => {
    if (x.level != 3) {
      arr.push({
        label: x.label,
        value: x.id,
        pid: x.pid
      })
    }
  })
  const newArr = proxy.$global.arrayToTree2(arr, "pid", "value", 0)
  console.log(newArr)
  return newArr
}

// 增加组件
const isAdd = ref(false)
const columns = ref([])
const form = ref(null)
function addCom() {
  form.value = {}
  isAdd.value = true
  getColumns('designs')
}

// 获取参数列表
function getColumns(table) {
  proxy.$service.getColumnList(table).then(res => {
    columns.value = proxy.$global.reSort(res.data, 'sort')
    columns.value.map(x => {
      if (x.name == 'pid') {
        x.options = options.value
      }
    })
  })
}

function submit(data) {
  data.create_time = proxy.$global.formatDataTime(new Date())
  proxy.$service.addData({ table: 'designs', data }).then(res => {
    isAdd.value = false
    testCom(data.name)
  })
}

function testCom(name) {
  const newHomeCom = codes.filter(x=> x.label == '桌面组件')[0].code
  let content = newHomeCom.replace(/demo/g, name)
  const path = __dirname.split('node')[0] + `src/renderer/src/components/home/${name}.vue`
  proxy.$system.writeFile(path, content).then(res => {
    proxy.$global.success('添加成功')
  })
}

function sortDesck() {
  isSort.value = true
}

const selectType = (y) => {
  typeIdx.value = y
}

const handleResize = () => {
  let screenWidth = window.innerWidth
  if (screenWidth < 700) {
    span.value = 24
  } else if (screenWidth > 600 && screenWidth < 1000) {
    span.value = 12
  } else if (screenWidth > 1000 && screenWidth < 1200) {
    span.value = 8
  } else if (screenWidth > 1200) {
    span.value = 6
  }
}

const getNewLisdt = (list) => {
  let params = []
  list.map((x, y) => {
    x.sort = y + 1
    params.push({
      id: x.id,
      pid: x.pid,
      sort: x.sort
    })
    if (x.children) {
      x.children.map((a, b) => {
        a.pid = x.id
        a.sort = b + 1
        params.push({
          id: a.id,
          pid: a.pid,
          sort: a.sort
        })
        if (a.children) {
          a.children.map((m, n) => {
            m.pid = a.id
            m.sort = n + 1
            params.push({
              id: m.id,
              pid: m.pid,
              sort: m.sort
            })
          })
        }
      })
    }
  })
  return params
}

function jungleArr(arr1, arr2) {
  const diff1 = arr1.filter(item1 => !arr2.some(item2 => JSON.stringify(item1) === JSON.stringify(item2)));
  return [...diff1];
}

const saveSort = () => {
  const sorts = jungleArr(getNewLisdt(designs.value), getNewLisdt(all.value))
  if (sorts.length > 0) {
    proxy.$service.treeSort({
      table: 'designs',
      sorts
    }).then(res => {
      isSort.value = false
      getDesign()
    })
  } else {
    proxy.$global.error('未修改！')
  }
}

</script>
<style scoped lang="scss">
$bg: rgba(13, 13, 13, 0.5);
$bg2: #1f2529;

.home {
  width: 100%;

  .descktop {
    width: 95%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 20px auto;

    .descktop-menu,
    .descktop-set {
      display: flex;
      height: 40px;
      margin: 10px 0;

      >div {
        height: 40px;
        margin-right: 20px;
        background-color: $bg;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 10px;
        position: relative;
        overflow: hidden;
        cursor: pointer;
        padding: 0 20px;

        >div {
          width: 100%;
          height: 2px;
          background-color: #1889fa;
          position: absolute;
          bottom: 0px;
        }
      }
    }
  }

  .descktop-content {
    width: 95%;
    margin: 0 auto;

    section {
      width: 100%;
      background-color: $bg;
      border-radius: 20px;
      padding: 20px;
      box-shadow: inset 0 0px 8px rgba(150, 150, 150, 0.5);
      margin-bottom: 10px;
    }
  }

  .link {
    >a {
      color: #fff;
      text-decoration: none;
    }
  }
}
</style>
